package com.lw.lost.activity.admin

import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.lw.lost.adapters.ManageFeedbackAdapter
import com.lw.lost.databinding.ActivityFeedbackManageBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.Feedback

class FeedbackManageActivity : AppCompatActivity() {

    private lateinit var binding: ActivityFeedbackManageBinding
    private lateinit var db: DBlost
    private lateinit var feedbackAdapter: ManageFeedbackAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityFeedbackManageBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "反馈管理"

        db = DBlost(this)
        setupRecyclerView()
        loadFeedbacks()
    }

    private fun setupRecyclerView() {
        feedbackAdapter = ManageFeedbackAdapter(
            onFeedbackClick = { feedback ->
                showFeedbackDetailDialog(feedback)
            },
            onActionClick = { feedback ->
                showActionDialog(feedback)
            }
        )

        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = feedbackAdapter
            addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL))
        }
    }

    private fun loadFeedbacks() {
        val cursor = db.feedbackDao.getAllFeedbacks()
        val feedbacks = mutableListOf<Feedback>()

        cursor.use { cursor ->
            while (cursor.moveToNext()) {
                feedbacks.add(
                    Feedback(
                        feedbackId = cursor.getLong(cursor.getColumnIndexOrThrow("feedbackId")),
                        userId = cursor.getLong(cursor.getColumnIndexOrThrow("userId")),
                        content = cursor.getString(cursor.getColumnIndexOrThrow("content")),
                        status = cursor.getInt(cursor.getColumnIndexOrThrow("status")),
                        feedbackTime = cursor.getString(cursor.getColumnIndexOrThrow("feedbackTime"))
                    )
                )
            }
        }

        updateUI(feedbacks)
    }

    private fun updateUI(feedbacks: List<Feedback>) {
        feedbackAdapter.submitList(feedbacks)

        // 更新统计信息
        val pendingFeedbacks = feedbacks.count { it.status == 0 }
        val processedFeedbacks = feedbacks.count { it.status == 1 }
        binding.tvFeedbackCount.text = "共 ${feedbacks.size} 条反馈（待处理: $pendingFeedbacks, 已处理: $processedFeedbacks）"

        // 更新空状态显示
        binding.tvEmpty.visibility = if (feedbacks.isEmpty()) View.VISIBLE else View.GONE
        binding.recyclerView.visibility = if (feedbacks.isEmpty()) View.GONE else View.VISIBLE
    }

    private fun showFeedbackDetailDialog(feedback: Feedback) {
        // 获取反馈用户信息
        val userCursor = db.userDao.getUserById(feedback.userId)
        val username = if (userCursor.moveToFirst()) {
            "${userCursor.getString(userCursor.getColumnIndexOrThrow("name"))} (${userCursor.getString(userCursor.getColumnIndexOrThrow("username"))})"
        } else "未知用户"
        userCursor.close()

        AlertDialog.Builder(this)
            .setTitle("反馈详情")
            .setMessage("""
                反馈用户：$username
                反馈时间：${feedback.feedbackTime}
                反馈内容：${feedback.content}
                处理状态：${if (feedback.status == 0) "待处理" else "已处理"}
            """.trimIndent())
            .setPositiveButton("确定", null)
            .show()
    }

    private fun showActionDialog(feedback: Feedback) {
        if (feedback.status == 1) {
            Toast.makeText(this, "该反馈已处理", Toast.LENGTH_SHORT).show()
            return
        }

        AlertDialog.Builder(this)
            .setTitle("处理反馈")
            .setMessage("确定要将该反馈标记为已处理吗？")
            .setPositiveButton("确定") { _, _ ->
                processFeedback(feedback.feedbackId)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun processFeedback(feedbackId: Long) {
        val result = db.feedbackDao.updateStatus(feedbackId, 1)
        if (result > 0) {
            Toast.makeText(this, "已处理反馈", Toast.LENGTH_SHORT).show()
            loadFeedbacks()
        } else {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
} 